package org.utils.ui;

import javax.swing.JTextField;

public class SizedTextField extends JTextField
{
	private static final long serialVersionUID = 3954573857180308856L;
	int mNumberOfChars;
		
    public SizedTextField(int nb)
    {
        super();	
        mNumberOfChars = nb;
    }
  
    public void setText(String strText)
    {
        if (strText != null)
            if ((mNumberOfChars > 0) && (strText.length() > mNumberOfChars))
                strText = strText.substring(0, mNumberOfChars);
        super.setText(strText);
    }
  
    public void replaceSelection(String strText)
    {
        if (mNumberOfChars > 0)
        {
            int nLength = 0;

            if (strText != null) {
                nLength += strText.length();
            }
            if (getText() != null) {
                nLength += getText().length();
            }
            if (getSelectedText() != null) {
                nLength -= getSelectedText().length();
            }
    
            if (nLength > mNumberOfChars) {
                getToolkit().beep();
                return;
            }
        }   
        super.replaceSelection(strText);
    }
} 
// End of class
